<?php
namespace app\api\model\wine;

use app\common\library\helper;
use app\common\model\BaseModel;

class Member extends BaseModel{
    protected $autoWriteTimestamp = true;

    private static function add(int $user_id)
    {
        $userArr = \app\common\model\User::where(['user_id'=>$user_id])->find();
        return self::create([
            'store_id' => getStoreId(),
            'user_id' => $user_id,
            'name' => '',
            'mobile' => $userArr['mobile'],
            'idCard' => '',
            'birthday' => 0,
            'sex' => 1,
            'age' => 18,
            'height' => 0,
            'weight' => 0,
            'province' => '湖南省',
            'city' => '长沙市',
            'area' => '岳麓区'
        ]);
    }

    // 编辑
    public static function edit(array $params)
    {
        $data = [];
        isset($params['name']) && $data['name'] = $params['name'];
        isset($params['mobile']) && $data['mobile'] = $params['mobile'];
        isset($params['idCard']) && $data['idCard'] = $params['idCard'];
        isset($params['birthday']) && $data['birthday'] = helper::checkTimer($params['birthday']);
        isset($params['sex']) && $data['sex'] = $params['sex'];
        isset($params['age']) && $data['age'] = $params['age'];
        isset($params['height']) && $data['height'] = $params['height'];
        isset($params['weight']) && $data['weight'] = $params['weight'];
        isset($params['province']) && $data['province'] = $params['province'];
        isset($params['city']) && $data['city'] = $params['city'];
        isset($params['area']) && $data['area'] = $params['area'];
        return self::where(['user_id' => $params['user_id']])
            ->save($data);
    }



    // 关联用户信息
    public function user(){
        return $this->hasOne(\app\common\model\User::class,'user_id','user_id')
            ->with('avatar')
            ->bind(['nick_name','avatar_url']);
    }

    // 查看个人信息
    public static function detail(int $user_id){
        // 判断个人信息是否存在
        $r = self::where(['user_id'=>$user_id])->findOrEmpty();
        if($r->isEmpty()){
            // 不存在则创建默认信息
            self::add($user_id);
        }
        return self::where(['user_id'=>$user_id])
            ->with('user')
            ->find();
    }
}
